package com.example.birdfriends.utils.search;

import com.example.birdfriends.pojo.post.Post;
import com.example.birdfriends.pojo.post.PostFront;
import com.example.birdfriends.service.PostService;
import com.example.birdfriends.service.UserService;
import com.example.birdfriends.utils.convert.ConvertService;
import com.example.birdfriends.utils.sort.Sort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SearchUtil {
    @Autowired
    private ConvertService convertService;
    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;

    public void addList1ToList2(List<Post> srcPosts, List<Post> dstPosts){
        // 目标链表为空，可以直接把数据放入目标链表中
        if(dstPosts.isEmpty()){
            dstPosts.addAll(srcPosts);
            return ;
        }
        // 目标链表不为空，判断当前链表数据是否在目标链表中，不在则放入目标链表，在则不处理
        // 遍历源链表
        List<Long> srcPids = new ArrayList<>();
        for(Post post: srcPosts){
            srcPids.add(post.getPid());
        }
        List<Long> dstPids = new ArrayList<>();
        for(Post post: dstPosts){
            dstPids.add(post.getPid());
        }

        // 遍历源链表
        for(int i = 0; i < srcPids.size(); i++){
            // 如果目标列表中已有了当前帖子，不需要将当前帖子加入目标链表
            if(!dstPids.contains(srcPids.get(i))){
                dstPosts.add(srcPosts.get(i));
            }
        }
    }

    @Autowired
    private Sort sort;
    public List<PostFront> searchPost(List<String> words, Long curLoginUid, String curPageName){
        List<Post> postList = new ArrayList<>();
        for (String word: words){
            List<Post> posts = postService.findPostsByTitleOrContent(word, word);
            addList1ToList2(posts, postList);
        }

        // 将贴子按照点赞数排序
        List<PostFront> postFrontList = convertService.posts2PostFronts(postList, curLoginUid, curPageName);
        return sort.sortPostByPraise(postFrontList);
    }
}
